package cn.itcast.nems.common.web.util;

import cn.itcast.nems.common.account.AccountInfo;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * author: yong.li
 * create: 2023-11-23 13:45:20
 **/
public class JwtTokenUtil {

    private final static String bearerPrefix = "Bearer ";

    /**
     * 通过用户登录的tokan解析用户信息
     *
     * @param jwtToken 由auth.itcast.cn颁发的jwt token
     * @return 账号信息
     */
    public static AccountInfo parseToken(String jwtToken) {
        try {
            if (jwtToken.startsWith(bearerPrefix)) {
                jwtToken = jwtToken.substring(bearerPrefix.length());
            }
            SignedJWT jwt = SignedJWT.parse(jwtToken);
            final JWTClaimsSet jwtClaimsSet = jwt.getJWTClaimsSet();
            return createAccountInfo(jwtClaimsSet);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static AccountInfo createAccountInfo(JWTClaimsSet jwtClaimsSet) {
        final Map<String, Object> claims = jwtClaimsSet.getClaims();
        AccountInfo info = new AccountInfo();
        String email = (String) claims.get("email");
        if (!StringUtils.hasText(email)) {
            email = (String) claims.get("preferred_username");
        }
        info.setEmail(email);
        String name = (String) claims.get("name");
        if (!StringUtils.hasText(name)) {
            name = (String) claims.get("given_name");
        }
        info.setName(name);
        String number = (String) claims.get("employeeNumber");
        if (!StringUtils.hasText(number)) {
            number = (String) claims.get("jobNumber");
        }
        info.setNumber(number);
        String departmentName = (String) claims.get("departmentName");
        info.setDepartmentName(departmentName);
        return info;
    }

}
